import angular from 'angular';
import treeSelectTemplate from './tree-select.template.html';

treeSelectDirective.$inject = ['$timeout', '$document'];

function treeSelectDirective($timeout, $document) {
  return {
    restrict: 'E',
    template: treeSelectTemplate,
    scope: {
      treeData: '=',
      id: '@',
      label: '@',
      cascade: '=?',
      multiple: '=?',
      cascadeReturnParentOnly: '=?',
      ngModel: '=',
      placeholder: '@',
      disabled: '=?',
      clearable: '=?'
    },
    link: function(scope, element) {
      // 默认配置
      scope.idField = scope.id || 'BpaId';
      scope.labelField = scope.label || 'cnName';
      scope.cascade = scope.cascade !== undefined ? scope.cascade : true;
      scope.multiple = scope.multiple !== undefined ? scope.multiple : true;
      scope.cascadeReturnParentOnly = scope.cascadeReturnParentOnly !== undefined ? scope.cascadeReturnParentOnly : false;
      scope.placeholder = scope.placeholder || '请选择';
      scope.disabled = scope.disabled || false;
      scope.clearable = scope.clearable !== undefined ? scope.clearable : true;

      // 状态
      scope.isOpen = false;
      scope.displayText = '';
      scope.selectedCount = 0;

      // 内部选中ID数组，用于与 multi-level-tree 通信
      scope.internalSelectedIds = [];

      // 节点映射
      var nodeMap = {};

      // 构建节点映射
      function buildNodeMap(nodes, parent) {
        if (!nodes || !angular.isArray(nodes)) return;

        nodes.forEach(function(node) {
          var nodeId = node[scope.idField];
          nodeMap[nodeId] = node;

          if (node.children && node.children.length > 0) {
            buildNodeMap(node.children, node);
          }
        });
      }

      // 更新显示文本
      function updateDisplayText() {
        if (!scope.internalSelectedIds || scope.internalSelectedIds.length === 0) {
          scope.displayText = '';
          scope.selectedCount = 0;
          return;
        }

        scope.selectedCount = scope.internalSelectedIds.length;

        if (scope.multiple) {
          // 多选: 显示"已选 N 项"
          scope.displayText = '已选 ' + scope.selectedCount + ' 项';
        } else {
          // 单选: 显示节点文本
          var nodeId = scope.internalSelectedIds[0];
          var node = nodeMap[nodeId];
          scope.displayText = node ? node[scope.labelField] : '';
        }
      }

      // 监听树数据变化
      scope.$watch('treeData', function(newVal) {
        if (newVal) {
          nodeMap = {};
          buildNodeMap(newVal);
          updateDisplayText();
        }
      }, true);

      // 监听外部 ngModel 变化，同步到内部
      scope.$watch('ngModel', function(newVal, oldVal) {
        // 使用 angular.equals 比较，避免引用相等问题
        if (!angular.equals(scope.internalSelectedIds, newVal)) {
          scope.internalSelectedIds = angular.copy(newVal || []);
          updateDisplayText();
        }
      }, true);

      // 监听内部选中数据变化，同步到外部 ngModel
      var lastInternalValue = [];
      scope.$watch('internalSelectedIds', function(newVal, oldVal) {
        // 检查内容是否真的变化了
        if (!angular.equals(lastInternalValue, newVal)) {
          lastInternalValue = angular.copy(newVal);

          // 使用 angular.equals 比较，避免引用相等问题
          if (!angular.equals(scope.ngModel, newVal)) {
            // 使用 splice 而不是赋值，保持引用
            if (scope.ngModel) {
              scope.ngModel.length = 0;
              Array.prototype.push.apply(scope.ngModel, newVal || []);
            } else {
              scope.ngModel = angular.copy(newVal || []);
            }
            updateDisplayText();

            // 单选模式下,选中后自动关闭
            if (!scope.multiple && newVal && newVal.length > 0 && scope.isOpen) {
              $timeout(function() {
                scope.isOpen = false;
              }, 200);
            }
          }
        }
      }, true);

      // 切换下拉状态
      scope.toggleDropdown = function($event) {
        if ($event) {
          $event.stopPropagation();
        }

        if (scope.disabled) {
          return;
        }

        scope.isOpen = !scope.isOpen;
      };

      // 清空选择
      scope.clearSelection = function($event) {
        if ($event) {
          $event.stopPropagation();
        }

        scope.internalSelectedIds.length = 0;
        if (scope.ngModel) {
          scope.ngModel.length = 0;
        }
        updateDisplayText();
      };

      // 点击外部关闭下拉
      var clickHandler = function(event) {
        if (!scope.isOpen) return;

        var targetElement = event.target;
        var clickedInside = element[0].contains(targetElement);

        if (!clickedInside) {
          $timeout(function() {
            scope.isOpen = false;
          });
        }
      };

      $document.on('click', clickHandler);

      // 清理事件监听
      scope.$on('$destroy', function() {
        $document.off('click', clickHandler);
      });

      // 判断是否显示清空按钮
      scope.showClearButton = function() {
        return scope.clearable && !scope.disabled &&
               scope.internalSelectedIds && scope.internalSelectedIds.length > 0;
      };
    }
  };
}

export default treeSelectDirective;
